# -*- coding: utf-8 -*-
# ㊎ Author : XMZ
# ㊍ Time   : 2023/09/27 027 15:14
# ㊌ File   : script-framework->config.py
# ㊋ IDE    : PyCharm
# ㊏ REMARKS:
import os
import random
from pathlib import Path
from urllib.parse import quote_plus

try:
    import tomllib
except ModuleNotFoundError:
    import tomli as tomllib

base_dir = Path(__file__).resolve().parent


# 工具函数-解配置参数
def get_nested(config, *keys, default=None):
    for key in keys:
        if isinstance(config, dict) and key in config:
            config = config[key]
        else:
            return default
    return config


# 加载配置文件
def load_config():
    env = os.environ.get('env', 'stg').strip().lower()  # stg 开发 dev 测试 prd 生产
    filename_map = {
        'stg': 'config.toml',
        'dev': 'config.dev.toml',
        'prd': 'config.prd.toml',
    }
    filename = filename_map.get(env, 'config.toml')
    config_file = base_dir / filename
    if not config_file.exists(): raise FileNotFoundError(f"配置文件未找到: {config_file}")
    # 打开配置文件
    with open(config_file, 'rb') as f:
        return tomllib.load(f)


_cfg = load_config()


class Settings:
    BASEDIR: str = Path(__file__).absolute().parent.parent
    LOG_PATH: str = os.path.join(BASEDIR, 'logs')
    # 系统
    __debug = get_nested(_cfg, 'system', 'debug', default=False)
    debug = True if __debug.lower() == 'true' else False

    # 数据库（stock）
    _db = get_nested(_cfg, 'mysql', 'stock', default={})
    host = _db.get('host', 'localhost')
    port = _db.get('port', 3306)
    username = _db.get('user', 'root')
    password = _db.get('password', '')
    databases = _db.get('databases', 'stock')

    @property
    def database_uri(self):
        pwd = quote_plus(self.password)
        return f"mysql+pymysql://{self.username}:{pwd}@{self.host}:{self.port}"

    @property
    def sqlalchemy_database_url(self):
        pwd = quote_plus(self.password)
        return f"mysql+aiomysql://{self.username}:{pwd}@{self.host}:{self.port}/{self.databases}?charset=utf8mb4"

    sql_lite_db = BASEDIR / 'sqlite_driver' / 'example.sqlite3.db'

    # 雪花ID
    datacenter = get_nested(_cfg, 'snow', 'data_center_id', default=1)
    worker = get_nested(_cfg, 'snow', 'worker_id', default=1)

    # 通知
    dd_token = get_nested(_cfg, 'pushNotif', 'dingtalk', default='').split(',')
    qw_token = get_nested(_cfg, 'pushNotif', 'qywechat', default='').split(',')

    @staticmethod
    def mysql(db_name: str) -> dict:
        db_cfg = get_nested(_cfg, 'mysql', db_name, default={})
        return {
            'host': db_cfg.get('host'),
            'port': db_cfg.get('port'),
            'username': db_cfg.get('user'),
            'password': db_cfg.get('password'),
            'databases': db_cfg.get('databases'),
        }

    @property
    def proxy(self):
        proxies = get_nested(_cfg, 'proxy', 'proxies', default=[])
        return f"http://{random.choice(proxies)}" if proxies else None


settings = Settings()

if __name__ == '__main__':
    print(type(settings.debug))